package com.zksite.nator.client.server.handler;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.util.ReferenceCountUtil;

@Component
@Scope("prototype")
public class ForwardHandle extends ChannelInboundHandlerAdapter {

	private Channel channel;

	private String forwardid;

	public void init(Channel channel, String forwardid) {
		this.channel = channel;
		this.forwardid = forwardid;
	}

	@Override
	public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
		if (msg instanceof FullHttpResponse) {
			FullHttpResponse response = (FullHttpResponse) msg;
			HttpHeaders headers = response.headers();
			headers.add("forwardid", forwardid);
		}
		ChannelFuture channelFuture = channel.writeAndFlush(msg);
		channelFuture.addListener(new ChannelFutureListener() {

			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				ctx.close();
			}

		});
	}

}
